package com.sgzn.sgpay.service.tcp.receive.handler;

import com.sgzn.sgpay.model.response.SgsResultResponse;
import com.sgzn.sgpay.service.tcp.api.TcpTerminalInitiativeBillIncrementExchangeService;
import com.sgzn.sgpay.service.tcp.model.terminal.request.TcpTerminalInitiativeBillIncrementExchangeRequest;
import com.sgzn.sgpay.service.tcp.receive.TcpReceiveCallHandlerTemplate;
import com.sgzn.sgpay.service.tcp.receive.modle.TcpReceiveCallRequest;
import com.sgzn.sgpay.service.tcp.receive.modle.response.TcpTerminalInitiativeBillIncrementExchangeResult;
import com.sgzn.sgpay.service.tcp.util.SgTcpUtil;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 终端主动上传账目增量（兑币机终端发起） 处理器
 * @author huangsenguang
 * @version Id: TcpTerminalInitiativeBillIncrementExchangeHandler.java, v 0.1 2018/7/30 13:55 huangsenguang Exp $$
 */
@Service
@Slf4j
public class TcpTerminalInitiativeBillIncrementExchangeHandler extends TcpReceiveCallHandlerTemplate<TcpTerminalInitiativeBillIncrementExchangeResult> {
    /**
     * 协议总字符数
     */
    @Getter
    private final int protocolLength = 36;

    @Resource
    private TcpTerminalInitiativeBillIncrementExchangeService tcpTerminalInitiativeBillIncrementExchangeService;

    @Override
    public TcpTerminalInitiativeBillIncrementExchangeResult callInner(TcpReceiveCallRequest request) {
        String data = request.getData();
        TcpTerminalInitiativeBillIncrementExchangeResult result = new TcpTerminalInitiativeBillIncrementExchangeResult();
        result.setIncreCode(data.substring(0,2));
        result.setErrorCode(data.substring(2,4));
        result.setIncomeIncrement(parse(data,4,8));
        result.setOutCoinIncrement(parse(data,8,12));
        result.setPresentCoinAmount(parse(data,12,16));
        return result;
    }

    @Override
    protected void handleAfter(TcpReceiveCallRequest request, TcpTerminalInitiativeBillIncrementExchangeResult result) {
        TcpTerminalInitiativeBillIncrementExchangeRequest tcpRequest = new TcpTerminalInitiativeBillIncrementExchangeRequest();
        tcpRequest.setDeviceId("10001");
        SgsResultResponse<String> sgsResponse = tcpTerminalInitiativeBillIncrementExchangeService.invoke(tcpRequest);
        log.info("14.终端主动上传账目增量应答（兑币机） :{}",sgsResponse.toString());
    }

    @Override
    protected int getProtocolLength(TcpReceiveCallRequest request) {
        return this.protocolLength;
    }

    private int parse(String data, int beginIndex, int endIndex) {
        return Integer.parseInt(SgTcpUtil.sortTcp(data.substring(beginIndex, endIndex)), 16);
    }
}

